package com.estylesoft.pshevch.fw;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;

import java.util.List;

public class HelperBase {
    private boolean acceptNextAlert = true;

    protected ApplicationManager appManager;
    protected WebDriver driver;

    public HelperBase(ApplicationManager appManager) {
        this.appManager = appManager;
        this.driver = appManager.getDriver();

    }

    public boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    public String closeAlertAndGetItsText() {
        try {
            Alert alert = driver.switchTo().alert();
            String alertText = alert.getText();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alertText;
        } finally {
            acceptNextAlert = true;
        }
    }

    public void setYesNoRadioButton(String buttonName, boolean flag) {
        driver.findElement(By.id(buttonName + "_" + (flag ? "yes" : "no"))).click();
    }

    public void fillTextField(By by, String text) {
        driver.findElement(by).clear();
        driver.findElement(by).sendKeys(text);
    }

    public void uploadFile(By by, String text) {
        driver.findElement(by).sendKeys(text);
    }

    public String getElementText(By by) {
        return driver.findElement(by).getText();
    }

    public void clickElement(By by) {
        driver.findElement(by).click();
    }

    public boolean containsPart(List<String> stringList, String inputString) {
        for (String nextString : stringList){
            if (nextString.contains(inputString))
                return true;
        }
        return false;
    }
}
